from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_user, logout_user, login_required, current_user
# 移除JWT导入，使用Flask-Login会话认证
from models import User
from extensions import db
from werkzeug.security import check_password_hash
import logging

logger = logging.getLogger('Personal_Blog_System')

# 创建认证路由蓝图
auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    """用户登录"""
    if request.method == 'POST':
        try:
            data = request.get_json() if request.is_json else request.form
            username = data.get('username')
            password = data.get('password')
            remember = data.get('remember', False)
            
            if not username or not password:
                if request.is_json:
                    return jsonify({'success': False, 'message': '用户名和密码不能为空'})
                flash('用户名和密码不能为空', 'error')
                return render_template('auth/login.html')
            
            user = User.query.filter_by(username=username).first()
            
            if user and user.check_password(password):
                if not user.is_active:
                    if request.is_json:
                        return jsonify({'success': False, 'message': '账户已被禁用'})
                    flash('账户已被禁用', 'error')
                    return render_template('auth/login.html')
                
                login_user(user, remember=remember)
                
                if request.is_json:
                    return jsonify({
                        'success': True, 
                        'message': '登录成功',
                        'user': {
                            'id': user.id,
                            'username': user.username,
                            'role': user.role
                        }
                    })
                
                next_page = request.args.get('next')
                return redirect(next_page) if next_page else redirect(url_for('main.index'))
            else:
                if request.is_json:
                    return jsonify({'success': False, 'message': '用户名或密码错误'})
                flash('用户名或密码错误', 'error')
                return render_template('auth/login.html')
                
        except Exception as e:
            logger.error(f"登录失败: {str(e)}")
            if request.is_json:
                return jsonify({'success': False, 'message': '登录失败，请稍后重试'})
            flash('登录失败，请稍后重试', 'error')
            return render_template('auth/login.html')
    
    return render_template('auth/login.html')

@auth_bp.route('/logout')
@login_required
def logout():
    """用户登出"""
    try:
        logout_user()
        flash('已成功登出', 'info')
        return redirect(url_for('main.index'))
    except Exception as e:
        logger.error(f"登出失败: {str(e)}")
        flash('登出失败', 'error')
        return redirect(url_for('main.index'))

# 注册功能已删除

